<template>
  <!-- 创建任务 -->
  <div class="addTask-box">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="目标">
        <el-input :value="getTargetName()" disabled></el-input>
      </el-form-item>
      <el-form-item prop="name" label="任务名标">
        <el-input v-model="form.name" placeholder="任务名标" :readonly="!isCanEdit()"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" required>
        <div class="selectTime">
          <el-col :span="12">
            <el-form-item prop="startDay">
              <el-date-picker
                v-model="form.startDay"
                type="date"
                placeholder="选择日期"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                class="selectDay"
                popper-class="selectRep"
                :readonly="!isCanEdit()"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1"></el-col>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-time-picker
                popper-class="selectRep"
                v-model="form.startTime"
                value-format="HH:mm"
                format="HH:mm"
                placeholder="选择时间"
                :readonly="!isCanEdit()"
              >
              </el-time-picker>
            </el-form-item>
          </el-col>
        </div>
      </el-form-item>
      <el-form-item label="结束时间" required>
        <div class="selectTime">
          <el-col :span="12">
            <el-form-item prop="endDay">
              <el-date-picker
                v-model="form.endDay"
                type="date"
                placeholder="选择日期"
                format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd"
                class="selectDay"
                popper-class="selectRep"
                :readonly="!isCanEdit()"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1"></el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-picker
                popper-class="selectRep"
                v-model="form.endTime"
                value-format="HH:mm"
                format="HH:mm"
                placeholder="选择时间"
                :readonly="!isCanEdit()"
              >
              </el-time-picker>
            </el-form-item>
          </el-col>
        </div>
      </el-form-item>
      <el-form-item prop="finalTime" label="截止时间" v-if="form.repeatDays != '-1'">
        <el-date-picker
          v-model="form.finalTime"
          type="date"
          placeholder="选择日期"
          format="yyyy年MM月dd日"
          value-format="yyyy-MM-dd"
          class="selectDay"
          popper-class="selectRep"
          :readonly="!isCanEdit()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="重复" prop="repeatDays">
        <el-select
          v-model="form.repeatDays"
          placeholder="请选择"
          popper-class="selectRep"
          class="selectDay"
          @change="changeRepeat"
          :disabled="!isCanEdit()"
        >
          <el-option label="不重复" value="-1"></el-option>
          <el-option label="工作日重复" value="0"></el-option>
          <el-option label="每周重复" value="8"></el-option>
          <el-option label="每天重复" value="9"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择星期" prop="weeks" v-if="form.repeatDays == '8'">
        <el-select
          multiple
          filterable
          default-first-option
          v-model="form.weeks"
          placeholder="请选择"
          popper-class="selectRep"
          class="selectDay"
          :disabled="!isCanEdit()"
        >
          <el-option label="星期一" value="1"></el-option>
          <el-option label="星期二" value="2"></el-option>
          <el-option label="星期三" value="3"></el-option>
          <el-option label="星期四" value="4"></el-option>
          <el-option label="星期五" value="5"></el-option>
          <el-option label="星期六" value="6"></el-option>
          <el-option label="星期日" value="7"></el-option>
        </el-select>
        <!-- <el-checkbox v-model="form.isAllDay">全天</el-checkbox> -->
      </el-form-item>
      <el-form-item label="参与者">
        <!-- <el-select
          v-model="form.userIds"
          multiple
          placeholder="参与者"
          popper-class="selectRep"
          class="selectMen"
          @change="selectUserIdsFn"
        >
          <el-option
            :label="user.nickname"
            :value="user.userId"
            v-for="user in userList"
            :key="user.userId"
          ></el-option>
        </el-select> -->
        <el-cascader v-model="selectUserIds" :options="circleList" :props="props" :show-all-levels="false" popper-class="selectRep" @change="cascaSel" :key="`addUser`" :disabled="!isCanEdit()"></el-cascader>
      </el-form-item>
      <!-- 指派给 -->
      <el-form-item label="指派给">
        <!-- <el-select
          v-model="form.principal"
          placeholder="指派给"
          popper-class="selectRep"
          class="selectMen"
        >
          <el-option
            :label="user.nickname"
            :value="user.userId"
            v-for="user in assignList"
            :key="user.userId"
          ></el-option>
        </el-select> -->
        <el-cascader v-model="radioPrincipal" :options="circleList" :props="radioProps" :show-all-levels="false" popper-class="selectRep" @change="cascaRadio" :key="`addPrincipal`" :disabled="!isCanEdit()"></el-cascader>
      </el-form-item>
      <el-form-item label="地点">
        <el-input v-model="form.address" placeholder="地点" :readonly="!isCanEdit()"></el-input>
      </el-form-item>
      <el-form-item label="提醒" prop="notice">
        <el-select
          v-model="form.notice"
          placeholder="提醒"
          popper-class="selectRep"
          class="selectMen"
          :disabled="!isCanEdit()"
        >
          <el-option label="不提醒" value="0"></el-option>
          <el-option label="提前5分钟" value="5"></el-option>
          <el-option label="提前15分钟" value="15"></el-option>
          <el-option label="提前30分钟" value="30"></el-option>
          <el-option label="提前1小时" value="60"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <!-- 富文本 -->
        <!-- <WangEditor :wangkey="1" ref="wangEditor" :list="form.describable"></WangEditor> -->
        <!-- 输入框 -->
        <el-input
          type="textarea"
          :rows="6"
          maxlength="490"
          placeholder="请输入内容"
          v-model="form.describable"
          :readonly="!isCanEdit()"
        ></el-input>

        <!-- 上传附件 -->
        <el-upload
          class="upload-demo"
          action="#"
          accept=".pdf,.xlsx,.pptx,.ppt,.doc,.docx,.jpg,.jpeg,.png"
          :auto-upload="false"
          :on-change="getSelectFileList"
          multiple
          :file-list="fileList"
          :show-file-list="false"
        >
          <h3>附件 <i class="el-icon-plus"></i></h3>
        </el-upload>
        <ul class="upload-list">
          <li v-for="(file, index) in selectFileList" :key="index">
            <el-input v-model="editFile.editname" @blur="rechFileBlur" v-if="editFileId == file.id"></el-input>
            <span @click="clickPreviewImg(file)" class="upload-span">{{file.name}}</span>
            <div class="upload-fn" v-if="isCanEdit()">
              <i @click="clickRech(file)" v-if="file.id">重命名</i>
              <i v-if="file.id">
                <a :href="file.url">下载</a>
              </i>
              <el-popconfirm title="确认删除该附件吗" icon-color="#f87a23" @confirm="removeFileList(file, index)">
                <i slot="reference">删除</i>
              </el-popconfirm>
            </div>
          </li>
        </ul>
      </el-form-item>
    </el-form>
    <SubBtn>
      <template slot="btn">
        <el-button round @click="batchDown" v-if="editObj.id"
          >下载附件</el-button
        >
        <el-button type="primary" round @click="save" v-if="isCanEdit()">保存</el-button>
      </template>
    </SubBtn>
    
    <!-- ----------------图片预览---------------- -->
    <el-image-viewer
      v-if="showFileSrcView"
      :initial-index="fileSrcIndex"
      :on-close="closeFileViewer"
      :url-list="fileSrcList"
    />
    <!-- ----------------图片预览----------------end -->

  </div>
</template>

<script>
import SubBtn from "@/components/subBtn/subBtn.vue";
import WangEditor from "@/wss/components/wangEditor.vue";
import {
  addServiceActionTaskApi,
  editServiceActionTaskApi
} from "@/BMViews/api/service/actionTask.js";
import { getSelectUserByCircleApi } from "@/BMViews/api/service/actionTarget.js";
import {
  getServiceTaskFileListApi,
  removeServiceTaskFileApi,
  updateFileNameTaskFileApi
} from "@/BMViews/api/service/taskFile.js";
// 获取所有问圈
import {getSelectCircleByUserIdApi} from "@/BMViews/api/financial/deposit.js"
import { timestampToTime } from "@/wss/utils/wss.js";

import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  name: "addTask",
  components: {
    SubBtn,
    WangEditor,
    ElImageViewer
  },
  props: {
    //当前选中的一条目标数据
    selectObj: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 当前编辑的这一条任务数据
    editObj: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      userList: [], //问圈成员列表
      assignList:[],//包含自己的问圈成员
      //当前编辑的表单
      form: {
        name: "", //任务名称
        startDay: "", //开始时间 天
        startTime: "", //开始时间 时间
        endDay: "", //结束时间 天
        endTime: "", //结束时间 时间
        repeatDays: "-1", //是否重复 默认不重复
        // isAllDay: false,//是否全天
        userIds: [], //参与者
        principal:'',//指派给
        address: "", //地点
        notice: "0", //提醒 默认不提醒
        describable: "" //描述
      },
      allUserList: [],//问圈所有用户列表
      selectFileList: [], //选择的列表
      fileList: [], //上传列表

      //级联选择器
      props: { 
        multiple: true,
        value: 'value',
        label: 'label',
        children: 'userList'
      }, 
      // 单选的
      radioProps:{
        value: 'value',
        label: 'label',
        children: 'userList'
      },
      selectUserIds: [],//已选的用户列表
      circleList: [], //获取问圈列表
      radioPrincipal:[],//单选的指派给谁

      // 表单验证
      rules: {
        name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
        startDay: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        endDay: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ],
        finalTime: [
          { required: true, message: "请选择截止时间", trigger: "change" }
        ],
        repeatDays: [
          { required: true, message: "请选择是否重复", trigger: "change" }
        ],
        weeks: [{ required: true, message: "请选择星期", trigger: "change" }],
        notice: [
          { required: true, message: "请选择是否提醒", trigger: "change" }
        ]
      },

      editFileId: '',//当前重命名附件的id
      editFile: {},//当前重命名的附件
      showFileSrcView: false,//是否显示图片预览
      fileSrcIndex: 0,//当前显示附件的index
      fileSrcList: [],//预览附件的图片
    };
  },
  async mounted() {
    await this.getSelectCircleByUserId()  // 获取所有问圈
    if (this.selectObj.circleId) {
      this.getSelectUserByCircle(); // 获取当前这个目标问圈的成员
    }
    if (this.editObj.id) {
      this.form = JSON.parse(JSON.stringify(this.editObj)); //获取当前编辑的表单
      this.form.notice = this.form.notice.toString(); //获取提前提醒时间

      // 获取已选用户
      this.echoUser() // 获取已选的参与者 找到问圈id 回显到级联选择器

      // 回显重复的数据
      if (this.form.repeatDays.includes("；")) {
        // weeks是选择的星期几
        this.$set(this.form, "weeks", this.form.repeatDays.split("；"));
        this.form.repeatDays = "8"; //每周重复
      }

      this.getServiceTaskFileList(); // 获取当前选择的这个任务的附件列表
    }
    if (this.editObj.startDay) {
      this.form.startDay = timestampToTime(this.editObj.startDay); //获取开始日期
    }
    if (this.editObj.endDay) {
      this.form.endDay = timestampToTime(this.editObj.endDay); //获取结束日期
    }
    if (this.editObj.startTime) {
      this.form.startTime = this.editObj.startTime; //获取开始时间
    }
    // 没有指派的人就默认获取自己
    if (!this.editObj.principal) {
      this.form.principal = this.$store.state.user.userId //默认获取自己
      this.radioPrincipal = [this.$store.state.user.circleId,this.$store.state.user.userId]
    }
  },
  watch: {
    // 监听form表单
    form: {
      deep: true,
      handler() {
        console.log(this.form.targetId, "form");
      }
    },
    // 监听当前选择的这个目标 
    selectObj: {
      deep: true,
      handler() {
        console.log(this.selectObj, "selectObj");
        if (this.selectObj.circleId) {
          this.getSelectUserByCircle(); // 获取当前这个目标问圈的成员
        }
      }
    },
    // 监听当前编辑的这一条任务数据
    editObj: {
      deep: true,
      async handler() {
        await this.getSelectCircleByUserId()  // 获取所有问圈
        console.log(this.editObj.targetId, "数据传过来了，xxxxxxxxxxxxxxxxxx");
        this.reset(); // 初始化form表单
        if (this.editObj.id) {
          this.form = JSON.parse(JSON.stringify(this.editObj)); //获取当前编辑的表单
          this.form.notice = this.form.notice.toString(); //获取提前提醒时间

          // 获取已选用户
          this.echoUser() // 获取已选的参与者 找到问圈id 回显到级联选择器

          // 回显重复的数据
          if (this.form.repeatDays.includes("；")) {
            // weeks是选择的星期几
            this.$set(this.form, "weeks", this.form.repeatDays.split("；"));
            this.form.repeatDays = "8"; //每周重复
          }

          this.getServiceTaskFileList(); // 获取当前选择的这个任务的附件列表
        }
        if (this.editObj.startDay) {
          console.log(
            timestampToTime(this.editObj.startDay),
            "llllllllllllllllllll"
          );
          this.form.startDay = timestampToTime(this.editObj.startDay); //获取开始日期
        }
        if (this.editObj.endDay) {
          this.form.endDay = timestampToTime(this.editObj.endDay); //获取结束日期
        }
        if (this.editObj.startTime) {
          this.form.startTime = this.editObj.startTime; //获取开始时间
        }
        if (this.editObj.endTime) {
          this.form.endTime = this.editObj.endTime; //获取结束时间
        }
        if (this.editObj.endTime) {
          this.form.endTime = this.editObj.endTime; //获取结束时间
        }
        // 没有指派的人就默认获取自己
        if (!this.editObj.principal) {
          this.form.principal = this.$store.state.user.userId //默认获取自己
          this.radioPrincipal = [this.$store.state.user.circleId,this.$store.state.user.userId]
        }
        this.$refs.form.resetFields();
      }
    },
    allUserList:{
      async handler(){
        // 一开始可能拿不到 this.allUserList,监听一旦变化就去过滤回显
        if(this.allUserList.length){
          this.echoUser() // 获取已选的参与者 找到问圈id 回显到级联选择器
        }                
      }
    },
  },
  methods: {
    // 判断当前能不能编辑
    isCanEdit(){
      // 当时编辑的时候才去做这个判断，添加的时候不做判断
      if(this.form.id){
        let userId = this.$store.state.user.userId
        // 判断是创建的人、指派的人、目标创建人可以编辑其他的都不行
        if(this.selectObj?.createBy){
          if(this.form.createBy==userId || this.form.principal==userId || this.selectObj.createBy==userId){
            return true
          }else{
            return false
          }
        }else{
          if(this.form.createBy==userId || this.form.principal==userId){
            return true
          }else{
            return false
          }
        }
      }else{
        return true
      }
    },

    // ----------------------------------参与者----------------------------------
    // 获取所有问圈
    async getSelectCircleByUserId(){
      let myself = true
      let result = await getSelectCircleByUserIdApi({myself})
      if (result.code == 200) {
        this.circleList = result.rows
        this.form.circleId = this.$store.state.user.userInfo.whereCircleId //获取当前问圈id

        this.allUserList = []
        await this.circleList.forEach(async (item)=>{
          let userList = await this.getSelectUserByCircleFn(item.circleId) // 获取当前问圈的成员
          this.$set(item,'userList',userList) //添加成员进去
          this.$set(item,'value',item.circleId) //添加获取的值
          this.$set(item,'label',item.masterName + '的圈子') //添加显示的值
        })
      }
    },

    // 获取当前问圈的成员
    async getSelectUserByCircleFn(circleId){
      let data = {
        type: '0,1',
        circleId: circleId
      }
        
      let result = await getSelectUserByCircleApi(data)
      if(result.code==200){
        // 先不过滤自己
        // let userList = result.rows.filter(item=>{
        //   return item.userId != this.$store.state.user.userId //过滤自己
        // })
        let userList = result.rows
        userList.forEach(item=>{
          this.$set(item,'value',item.userId) //添加获取的值
          this.$set(item,'label',item.nickname) //添加显示的值
          // item.value = item.userId //添加获取的值
          // item.label = item.nickname //添加显示的值
        })
        this.allUserList = [...this.allUserList,...userList] //获取所有用户列表
        return userList
      }
    },

    // 获取已选的参与者 找到问圈id 回显到级联选择器
    echoUser(){
      this.selectUserIds = []
      if(!this.form.userList) return
      this.$set(this.form,'userIds',[]) //清空之前的用户数据
      this.form.userList.forEach(item => {
        let obj = this.allUserList.find(k=>{
          return k.userId == item.userId
        })
        if(obj){
          // 如果已经包含了就不用再进去了
          if(item.type=='1'||item.type=='2'){
            this.selectUserIds.push([obj.circleId,obj.userId]) //添加回显级联数据
            this.form.userIds.push(obj.userId) //添加已选的用户数据
          }
        }
      })

      // 回显指派的人  radioPrincipal
      if(this.form.principal){
        let obj = this.allUserList.find(item=>{
          return item.userId == this.form.principal
        })
        if(obj){
          this.radioPrincipal = [obj.circleId,obj.userId]
        }
      }
    },

    // 选择参与者
    cascaSel(){
      let userIds = []
      this.selectUserIds.forEach(item=>{
        if(!userIds.includes(item[1])){
          userIds.push(item[1])
        }
      })
      this.$set(this.form,'userIds',userIds)
    },

    // 选择指派人
    cascaRadio(e){
      this.form.principal = e[1]
    },
    // ----------------------------------参与者----------------------------------end
    
    // 初始化form表单
    reset() {
      // 清空表单验证
      this.$refs.form.resetFields()
      // 初始化form
      this.form = {
        name: "", //任务名称
        startDay: "", //开始时间 天
        startTime: "", //开始时间 时间
        endDay: "", //结束时间 天
        endTime: "", //结束时间 时间
        repeatDays: "-1", //是否重复
        // isAllDay: false,//是否全天
        userIds: [], //参与者
         principal:this.$store.state.user.userId,//指派给
        address: "", //地点
        notice: "0", //提醒
        describable: "" //描述
      };
      this.selectFileList = []; //选择的列表
    },

    // 获取当前这个目标问圈的成员
    async getSelectUserByCircle() {
      let data = {
        type: "1",
        circleId: this.selectObj.circleId
      };
      let result = await getSelectUserByCircleApi(data);
      if (result.code == 200) {
        this.userList = result.rows;
        // 获取的问圈成员是没有自己的，默认指派给自己所以要将自己也加到成员中
        let arr=[{userId:this.$store.state.user.userId,nickname:this.$store.state.user.userInfo.nickName}]
        this.assignList=[...result.rows,...arr]
      }
    },

    // 获取当前选择的这个任务的附件列表
    async getServiceTaskFileList() {
      let taskId = this.editObj.id;
      let result = await getServiceTaskFileListApi({ taskId });
      if (result.code == 200) {
        // console.log(result.rows,'获取当前选择的这个任务的附件列表');
        this.selectFileList = result.rows;
      }
    },

    // 修改参与者全部没有的时候给个提示
    selectUserIdsFn(e) {
      if (!e.length) {
        this.$message({
          message: "当参与者为空时(只剩自己)，将解散群聊，并且不保留聊天记录",
          type: "warning",
          duration: 3000
        });
      }
    },

    // 修改成重复的时候
    changeRepeat(e){
      if(e != '-1'){
        // 如果是重复获取明年的今天
        const date = new Date();
        let year = date.getFullYear(); //获取年
        let month = date.getMonth() + 1; //获取月
        let day = date.getDate(); //获取日
        this.form.finalTime = `${year+1}-${month}-${day}`
      }else{
        // 不重复的清除截止时间
        this.form.finalTime = ''
      }
    },


    // 获取任务目标的名字
    getTargetName() {
      if (this.selectObj.id) {
        return `${this.selectObj.name}`;
      } else {
        return `${this.editObj.targetName}`;
      }
    },

    // 上传附件的钩子
    getSelectFileList(file, fileList) {
      //上传判断
      const isFormat =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "application/pdf" ||
        file.raw.type === "application/msword" ||
        file.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document"||
        file.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.raw.type === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ||
        file.raw.type === "application/vnd.ms-powerpoint";
      const isLt2M = file.raw.size / 1024 / 1024 < 10;
      
      if (!isFormat) {
        this.$message.error("只支持pdf、xlsx、pptx、ppt、doc、docx、jpg、jpeg、png格式!");
        return;
      } else {
        if (!isLt2M) {
          this.$message.error("上传附件大小不能超过 10MB!");
          return;
        } else {
          if (fileList && fileList.length > 1) {
            fileList.shift();
          }
          this.selectFileList.push(file); //把当前上传的文件添加到文件列表里面
          this.$emit("drawerBottom"); // 文件有动静就滚动到底部
        }
      }
    },

    // 重命名附件的回调
    clickRech(file){
      if(!this.editFileId){
        let arr = file.name.split('.')
        this.editFile = JSON.parse(JSON.stringify(file))
        this.$set(this.editFile,'editname',arr[0])
        this.$set(this.editFile,'editSuffix',arr[1])
        this.editFileId = file.id
      }else{
        this.editFileId = ''
      }
    },

    // 失去焦点保存
    rechFileBlur(){
      if(!this.editFile.editname){
        this.editFileId = ''
        this.$message({ message: "附件名称不能为空", type: "warning" });
        return
      }
      this.updateFileNameTaskFile() // 重命名附件的接口
    },

    // 重命名附件的接口
    async updateFileNameTaskFile(){
      let data = {
        id: this.editFile.id,//id
        name: this.editFile.editname + '.' + this.editFile.editSuffix //附件名字+后缀
      }
      let result = await updateFileNameTaskFileApi(data)
      if(result.code==200){
        this.editFileId = ''
        this.getServiceTaskFileList(); // 获取当前选择的这个任务的附件列表
        this.$message({ message: "修改成功", type: "success" });
      }
    },

    //删除一条附件
    async removeFileList(file, index) {
      // this.$confirm("是否删除该文件?", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      //   customClass: 'isConfirm'
      // })
      //   .then(async () => {
          
      //   })
      //   .catch(() => {});
      if (file.id) {
        await this.removeServiceTaskFile(file); // 删除附件的接口
        this.selectFileList.splice(index, 1); //不刷新列表，前端删除掉那一条就行
      } else {
        this.selectFileList.splice(index, 1);
      }
    },

    // 删除附件的接口
    async removeServiceTaskFile(file) {
      let result = await removeServiceTaskFileApi(file);
      if (result.code == 200) {
      }
    },

    // 判断重复返回对应的值
    isRepet() {
      if (this.form.repeatDays == "8") {
        let arr = this.form.weeks.sort((a, b) => Number(a) - Number(b)); //正序
        let repeat = arr.join("；"); //用中文分号拼接
        if (repeat == "1；2；3；4；5") {
          return 0; // 是工作日
        } else if (repeat == "1；2；3；4；5；6；7") {
          return 9; // 是每天重复
        } else {
          return repeat; //返回选择的那几天
        }
      } else {
        return this.form.repeatDays;
      }
    },

    // 点击保存按钮
    save() {
      this.$refs.form.validate(async(result)=>{
        // 表单验证成功要走的逻辑
       if(result){
          let formDate = new FormData();
          if (this.form.id) {
            formDate.set("id", this.form.id); //当前编辑的这一条id
          }
          if (this.form.sessionId) {
            formDate.set("sessionId", this.form.sessionId); //会话id
          }
          if (this.form.repeatDays!='-1' && this.form.finalTime) {
            formDate.set("finalTime", this.form.finalTime); //截止时间
          }
          formDate.set("createBy", this.$store.state.user.userId); //创建人的id
          formDate.set("name", this.form.name); //任务名称
          formDate.set("startDay", this.form.startDay.trim()); //开始时间 天
          formDate.set("startTime", this.form.startTime); //开始时间 时间
          formDate.set("endDay", this.form.endDay.trim()); //结束时间 天
          formDate.set("endTime", this.form.endTime); //结束时间 时间
          formDate.set("userIds", this.form.userIds); //参与者
          formDate.set("principal", this.form.principal); //指派给
          formDate.set("address", this.form.address); //地点
          formDate.set("notice", this.form.notice); //提醒
          formDate.set("describable", this.form.describable); //描述
          formDate.set("targetType", "1"); //目标的类型
          formDate.set("targetId", this.form.targetId || this.selectObj.id); //目标的id
          this.selectFileList.forEach((item, i) => {
            if (item.raw) {
              formDate.append(`file`, item.raw);
            }
          });
          // 判断重复 // 判断重复返回对应的值
          let reprat = this.isRepet();
          formDate.set("repeatDays", reprat); //是否重复

          //打印formDate
          // for (var key of formDate.entries()) {
          //     console.log(key[0] + ', ' + key[1]);
          // }
          // 发请求
          if (this.form.id) {
            // 编辑
            console.log(this.form, "form");
            this.editServiceActionTask(formDate); // 编辑一个任务的接口
          } else {
            // 添加
            this.addServiceActionTask(formDate); // 添加一个任务的接口
          }
         }
      });
    },

    // 添加一个任务的接口
    async addServiceActionTask(formDate) {
      let result = await addServiceActionTaskApi(formDate);
      if (result.code == 200) {
        this.$emit("reqOrClose");
        this.$message({ message: "添加成功", type: "success" });
      }
    },

    // 编辑一个任务的接口
    async editServiceActionTask(formDate) {
      let result = await editServiceActionTaskApi(formDate);
      if (result.code == 200) {
        this.$emit("reqOrClose");
        this.$message({ message: "编辑成功", type: "success" });
      }
    },

    // 点击下载附件
    batchDown() {
      // 过滤出有url的文件
      let list = this.selectFileList.filter(item => {
        if (item.url) {
          return item;
        }
      });
      // 判断
      if (!list.length) {
        this.$message({ message: "当前没有文件可以下载", type: "warning" });
        return;
      }
      // 循环调用
      list.forEach(item => {
        this.downloadFile(item.url);
      });
    },

    // 下载文件的方法
    downloadFile(url) {
      const iframe = document.createElement("iframe");
      iframe.style.display = "none"; // 防止影响页面
      iframe.style.height = 0; // 防止影响页面
      iframe.src = url;
      document.body.appendChild(iframe);
      setTimeout(() => {
        iframe.remove();
      }, 5 * 60 * 1000);
    },

    // 点击查看附件详情 selectFileList
    clickPreviewImg(file){
      // ----------获取所有附件图片列表----------
      this.fileSrcList = []
      this.selectFileList.forEach(item=>{
        let arr = item.url.split('.') //分割
        let sew = arr[arr.length-1] //后缀
        if(sew == 'jpg' || sew == 'jpeg' || sew == 'png'){
          this.fileSrcList.push(item.url)
        }
      })
      // ----------获取所有附件图片列表----------end

      // ----------点击查看的当前附件----------
      console.log(file,'点击查看附件详情点击查看附件详情');
      let arr = file.url.split('.')
      let sew = arr[arr.length-1]
      if(sew == 'jpg' || sew == 'jpeg' || sew == 'png'){
        this.fileSrcIndex = this.fileSrcList.findIndex((k) => k == file.url)
        this.showFileSrcView = true;
      }
      // ----------点击查看的当前附件----------end
    },

    // 关闭预览图片
    closeFileViewer() {
      this.showFileSrcView = false;
    },

  }
};
</script>

<style lang="scss" scoped>
p,
h3,
ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.addTask-box {
  padding: 0 20px;
  .el-form {
    margin-bottom: 80px;
  }
  .el-form-item {
    ::v-deep .el-form-item__label {
      &::before {
        display: none;
      }
    }
  }
  .el-select {
    width: 100%;
  }
  .el-cascader{
    width: 100%;
  }
  .el-textarea {
    ::v-deep .el-textarea__inner {
      font-family: Microsoft Yahei;
    }
  }
}

// 时间选择器
.selectTime {
  display: flex;
  .el-col {
    padding: 0 !important;
  }
}
.selectDay {
  width: 100%;
}
.selectMen {
  width: 100%;
}
</style>
<style scoped>
/* 选择附件 */
.el-tooltip__popper {
  max-width: 60% !important;
}
.upload-demo {
}
.upload-demo h3 {
  font-size: 14px;
  color: #909aaa;
  margin-top: 20px;
  margin-bottom: 10px;
  cursor: pointer;
}
.upload-list li {
  display: flex;
  align-items: center;
  position: relative;
  font-size: 12px;
  line-height: 30px;
  padding: 5px 0;
  color: #2e405e;
  border-bottom: 1px solid #efefef;
}
.upload-list li .upload-span{
  width: calc(100% - 120px);
  line-height: 20px;
  cursor: pointer;
}
.upload-list li>a,
.upload-list li>.el-input{
  width: calc(100% - 80px);
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}
.upload-list li .upload-fn{
  margin-left: auto;
}
.upload-list li i {
  color: #f87a23;
  font-style: normal;
  cursor: pointer;
  margin-left: 10px;
}

.upload-list li .tooltip-div {
  display: none;
  width: 100%;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 4px;
  top: 30px;
  left: 0;
  /* z-index: 10003; */
  padding: 15px;
}
.upload-list li .tooltip-div h3 {
  margin: 0;
  color: #fff;
  font-weight: 400;
  font-size: 12px;
  border-bottom: 1px solid #535151;
  padding-bottom: 8px;
  margin-bottom: 8px;
}
.upload-list li .tooltip-div p {
  color: #fff;
  line-height: 20px;
}
.upload-list li .tooltip-div > i {
  position: absolute;
  top: -16px;
  left: 20px;
  width: 0;
  height: 0;
  border: 8px solid rgba(0, 0, 0, 0.8);
  border-top-color: transparent;
  border-left-color: transparent;
  border-right-color: transparent;
}
.upload-list li:hover .tooltip-div {
  display: inline-block;
}

/* 选择附件 end */

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 10px 30px !important;
  z-index: 10002 !important;
}
::v-deep .subBtn > .el-button {
  width: 100px;
  padding: 10px 0 !important;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn > .el-button.el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
</style>
<style>
.selectRep {
}
.selectRep li {
  padding: 0 15px;
}

.el-popconfirm .el-button{
  color: #f87a23;
}
.el-popconfirm .el-button--primary{
  color: #fff;
  background-color: #f87a23;
  border-color: #f87a23;
}
.el-image-viewer__wrapper{
  z-index: 9999 !important;
}
</style>
